package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.TdmFileService;
import com.kingyun.gpsinspection.purificationservice.services.hbaseservice.HbaseUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.*;

/**
 * Created by yangcs on 2016/8/7.
 */
public class TdmFileServiceImpl implements TdmFileService {
    private static Logger logger = LoggerFactory.getLogger(TdmFileServiceImpl.class);

    @Autowired
    private TdmFileMapper tdmFileMapper;

    /**
     * 附件插入hbase中
     *
     * @param request
     * @param filename
     * @return
     * @throws Exception
     */
    @Override
    public String[] uploadImg(HttpServletRequest request, String filename) throws Exception {
        String hbasepath = null;
        if (filename.indexOf(".") > -1) {
            String suffix = filename.substring(filename.indexOf("."));
            // java 生成四位随机数
            // int i=(int)(Math.random()*9000)+1000;
            // int i= new java.util.Random().nextInt(9000)+1000;也可以
            hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            logger.info("HBase Application Running");
            HbaseUtils userUtils = context.getBean(HbaseUtils.class);
            userUtils.initialize("file");
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = request.getInputStream().read(buffer))) {
                output.write(buffer, 0, n);
            }
            userUtils.addOrg(hbasepath, output.toByteArray());
            return new String[]{hbasepath, filename};
        } else {
            return new String[]{"error", filename};
        }
    }

    /**
     * 插入附件信息到附件表
     *
     * @param businessId
     * @param filenames
     * @param fileHbasePaths
     * @return
     */
    @Override
    public int insertFile(String businessId, String[] filenames, String[] fileHbasePaths) throws Exception {
        int j = 0;
        if (filenames != null && filenames.length > 0) {
            List<File> list = new ArrayList<File>();
            File file;
            for (int i = 0; i < filenames.length; i++) {
                file = new File();
                file.setFileId(UniqueUtil.uuid());
                file.setBusinessId(businessId);
                file.setFileName(filenames[i]);
                file.setFileType((short) FileTypeUtil.getFileTypeByFileName(filenames[i]));
                file.setFileHbasePath(fileHbasePaths[i]);
                list.add(file);
            }
            j = tdmFileMapper.insertByList(list);
        }
        return j;
    }

    /**
     * 根据附件id查询附件所有信息
     *
     * @param fileId
     * @return
     */
    @Override
    public File queryById(String fileId) throws Exception {
        if (StringUtils.isBlank(fileId)) {
            return null;
        }
        File file = tdmFileMapper.selectByPrimaryKey(fileId);

        return file;
    }


    /**
     * 根据业务id查询附件表
     *
     * @param businessId
     * @return
     */
    @Override
    public List<File> queryByBusinessId(String businessId) throws Exception {
        return tdmFileMapper.queryByBusinessId(businessId);
    }

    /**
     * 根据主键删除附件
     *
     * @param fileId
     * @return
     */
    @Override
    public int delById(String fileId) throws Exception {
        if (StringUtils.isBlank(fileId)) {
            return 0;
        }

        int i = tdmFileMapper.deleteByPrimaryKey(fileId);

        return i;
    }

    /**
     * 根据业务id删除附件表
     *
     * @param businessId
     * @return
     */
    @Override
    public int delByBusinessId(String businessId) throws Exception {
        return tdmFileMapper.delByBusinessId(businessId);
    }

    /**
     * 根据hbasepath删除附件表记录
     *
     * @param fileHbasePath
     * @return
     */
    @Override
    public int delByFileHbasePath(String fileHbasePath) {
        return tdmFileMapper.delByFileHbasePath(fileHbasePath);
    }

    /**
     * 根据业务ID和trait查询
     *
     * @param map
     * @return
     */
    @Override
    public List<File> queryByBusinessIdTrait(Map map) {
        if (map == null) {
            return null;
        }

        List<File> list = tdmFileMapper.queryByBusinessIdTrait(map);

        return list;
    }

}
